package com.example.sakurasay.debtledger

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.foundation.background
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.outlined.AccountBalanceWallet
import androidx.compose.material.icons.outlined.ArrowDownward
import androidx.compose.material.icons.outlined.ArrowUpward
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@OptIn(ExperimentalMaterial3Api::class)
enum class DebtType {
    IOwe,
    OwesMe
}

enum class DebtStatus {
    Paid,
    Unpaid
}

data class Debt(
    val id: Int,
    val person: String,
    val amount: Double,
    val type: DebtType,
    val date: String,
    val description: String,
    val status: DebtStatus
)

val sampleDebts = listOf(
    Debt(1, "张三", 150.0, DebtType.OwesMe, "2023-10-25", "午餐", DebtStatus.Unpaid),
    Debt(2, "信用卡", 2500.0, DebtType.IOwe, "2023-10-28", "月度账单", DebtStatus.Unpaid),
    Debt(3, "李四", 50.0, DebtType.IOwe, "2023-10-20", "电影票", DebtStatus.Paid),
)

@Composable
fun DebtLedgerScreen() {
    var showAddSheet by remember { mutableStateOf(false) }
    val debts = remember { mutableStateListOf(*sampleDebts.toTypedArray()) }


    Box(modifier = Modifier.fillMaxSize()) {
        LazyColumn(
            contentPadding = PaddingValues(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            items(debts) { debt ->
                DebtListItem(debt = debt)
            }
        }
        FloatingActionButton(
            onClick = { showAddSheet = true },
            containerColor = MaterialTheme.colorScheme.primary,
            contentColor = MaterialTheme.colorScheme.onPrimary,
            modifier = Modifier.align(Alignment.BottomEnd).padding(16.dp),
        ) {
            Icon(Icons.Default.Add, contentDescription = "Add Debt")
        }

        if (showAddSheet) {
            AddDebtBottomSheet(
                onDismiss = { showAddSheet = false },
                onSave = { newDebt ->
                    debts.add(newDebt)
                    showAddSheet = false
                }
            )
        }
    }
}

@Composable
fun DebtListItem(debt: Debt) {
    val amountColor = if (debt.type == DebtType.OwesMe) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error
    val statusText = if (debt.status == DebtStatus.Unpaid) "未还清" else "已还清"
    val statusColor = if (debt.status == DebtStatus.Unpaid) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)

    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant,
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 12.dp)
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(
                imageVector = Icons.Outlined.AccountBalanceWallet,
                contentDescription = "Debt Icon",
                tint = MaterialTheme.colorScheme.secondary,
                modifier = Modifier.size(40.dp)
            )

            Spacer(modifier = Modifier.width(16.dp))

            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = debt.person,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "¥${"%.2f".format(debt.amount)}",
                    style = MaterialTheme.typography.bodyLarge,
                    fontWeight = FontWeight.SemiBold,
                    color = amountColor
                )
            }

            Text(
                text = statusText,
                style = MaterialTheme.typography.bodySmall,
                color = statusColor,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddDebtBottomSheet(
    onDismiss: () -> Unit,
    onSave: (Debt) -> Unit
) {
    val sheetState = rememberModalBottomSheetState()
    var person by remember { mutableStateOf("") }
    var amount by remember { mutableStateOf("") }
    var description by remember { mutableStateOf("") }
    var selectedDebtType by remember { mutableStateOf(DebtType.IOwe) }

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState
    ) {
        Column(modifier = Modifier.padding(16.dp).navigationBarsPadding()) {
            Text(
                text = "添加新的账目",
                style = MaterialTheme.typography.headlineSmall,
                modifier = Modifier.padding(bottom = 16.dp)
            )

            SingleChoiceSegmentedButtonRow(
                modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp)
            ) {
                SegmentedButton(
                    shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2),
                    onClick = { selectedDebtType = DebtType.IOwe },
                    selected = selectedDebtType == DebtType.IOwe
                ) {
                    Text("我欠别人")
                }
                SegmentedButton(
                    shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2),
                    onClick = { selectedDebtType = DebtType.OwesMe },
                    selected = selectedDebtType == DebtType.OwesMe
                ) {
                    Text("别人欠我")
                }
            }

            TextField(
                value = person,
                onValueChange = { person = it },
                label = { Text("对象") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            TextField(
                value = amount,
                onValueChange = { amount = it },
                label = { Text("金额") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(8.dp))
            TextField(
                value = description,
                onValueChange = { description = it },
                label = { Text("描述") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(
                onClick = {
                    val newDebt = Debt(
                        id = (0..1000).random(), // Replace with proper ID generation
                        person = person,
                        amount = amount.toDoubleOrNull() ?: 0.0,
                        type = selectedDebtType,
                        date = "2023-10-28", // Replace with actual date
                        description = description,
                        status = DebtStatus.Unpaid
                    )
                    onSave(newDebt)
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("保存")
            }
        }
    }
}